/* eslint-disable max-len */
import 'reflect-metadata';
import React from 'react';
import {
  setUmiHooks, IObject, injectBusinessComponents, udp,
} from '@cscec/udp-ui';
import {
  Navigate,
  Outlet,
  connect,
  getDvaApp,
  history,
  useDispatch,
  useSelector,
  useStore,
  useModel,
} from '@umijs/max';
import loadingCpt from '@/components/pageLoading';
import routeConfig from '../route';
import './components/editor/init';

setUmiHooks(() => ({
  connect,
  useDispatch,
  useStore,
  useSelector,
  getDvaApp,
  history,
  useModel,
}));
injectBusinessComponents();

/**
 * 动态加载页面组件
 * webpackExclude不要删除，该配置可以屏蔽加载多余的依赖，
 * 详情可以参考： https://webpack.js.org/api/module-methods/#dynamic-expressions-in-import
 * @param path 组件路径
 */
function loadComponent(path: string) {
  const realPath = path.replace('@', '');

  return React.lazy(
    () => import(
      /* webpackExclude: /(\.*\model\.tsx)|(\.*\.(ts|ejs|js|json|css|less|scss))$/, webpackChunkName:'pages/[request]' */
      `@/pages/${realPath}`
    ),
  );
}

/**
 * 格式化路由
 * @param menus 路由数组
 */
function parseRoute(menus: any[], { title = '' }: { title?: string } = {}) {
  const newRoutes: any = [];
  menus.forEach(
    (menu: { microApp?: any; path?: any; component?: any; children?: any; routes?: any; name?: any; query?: any }) => {
      const {
        path, component, children, routes, name, query,
      } = menu;
      const currentTitle = title || name;
      const routeChild = children || routes;
      const hasChildren = !!routeChild?.length;
      if (component) {
        const route: any = {
          exact: true,
          title: currentTitle,
          path: path || (hasChildren ? `/${routeChild[0].path?.match(/\/(.+?)\//)?.[1] || ''}` : '/'),
          query,
          element: (
            <React.Suspense fallback={loadingCpt({})}>
              {React.createElement(loadComponent(component), { children: hasChildren ? <Outlet /> : null })}
            </React.Suspense>
          ),
        };
        if (hasChildren) {
          route.children = parseRoute(routeChild, { title: currentTitle });
          route.exact = false;
        }
        newRoutes.push(route);
      } else if (hasChildren) {
        Array.prototype.push.apply(newRoutes, parseRoute(routeChild, { title: currentTitle }));
      } else if (menu.microApp) {
        newRoutes.push(menu);
      }
    },
  );
  newRoutes.length > 0 && newRoutes.push({ path: '', element: <Navigate to={newRoutes[0].path} replace /> });
  return newRoutes;
}

/**
 * 动态修改路由
 * @param routes 默认路由
 */
export function patchClientRoutes({ routes }: IObject) {
  const childRoutes = parseRoute(routeConfig, { title: '' });
  const routeLen = routes.length;
  if (routeLen > 0) {
    routes[routeLen - 1].children = childRoutes;
  } else {
    Array.prototype.push.apply(routes, childRoutes);
  }
  routes.push({ path: '*', element: <Navigate to="/portal/design" replace /> });
}

export function onRouteChange() { }

export const qiankun = {
  mount(props: any) {
    const masterInfo = props?.getMasterInfo?.();
    if (!masterInfo) return;
    udp.setUser({ ...masterInfo.getUser() });
    udp.registerExternal({
      getMasterObserver() {
        return masterInfo.getObserver?.();
      },
    });
  },
};

export async function getInitialState() {
  // token支持通过key传递过来
  const key = udp.getQueryValue('key');
  if (key) {
    udp.setUser({
      ...udp.getUser(),
      accessToken: key
    });
  } else if (process.env.NODE_ENV === 'development') {
    // 模拟登录
    const [success, user] = await udp.request.postWithArray({
      url: `portal/login/devLoginPost`,
      data: {
        userCode: "YG1010",
        password: udp.sm4.encode('Zjsk@dev')
      },
      requestType: 'json'
    });
    udp.setUser(
      success
        ? {
          ...user
        }
        : {
          accessToken:
            'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJhdWQiOiIiLCJjbGllbnR0eXBlIjoiMSIsIm5iZiI6MTcyMjgxOTgxNSwiY2xpZW50aWQiOiJVRFAtV0VCIiwic3lzdGVtQ29kZSI6IlVEUF83NiIsImlzcyI6IlVEUCIsImV4cCI6MTcyMjg2MzYxNSwidXNlcmlkIjoiMTExIiwiY3JlYXRlZHQiOiJNb24gQXVnIDA1IDA5OjEzOjM1IENTVCAyMDI0IiwianRpIjoiMzkxODAxYmMtYWNjMS00NTc3LWFiOWYtZmJjNmI1ZWFkZDNkIn0.36FXFzQBkFjtZvUbQ_gXgWd9trjBcZenyXPifCUzCbo'
        }
    );
  }
  if (!udp.getUser()?.accessToken) {
    // 子应用单独打开时，需要跳转到主应用的登录页，暂时这样处理
    window.location.replace('/udpweb/portal/index.html#/login');
  }
}
